package subject_set.offer100;

/**
 * @author haomin
 * @date 2022/10/20 15:15
 **/
public class Offer37 {
    public class Codec {

        // Encodes a tree to a single string.
        public String serialize(TreeNode root) {
            StringBuffer sb = new StringBuffer();
            if(root == null) return "&,";
            else {
                sb.append(root.val).append(",");
                sb.append(serialize(root.left));
                sb.append(serialize(root.right));
            }
            return sb.toString();
        }

        // Decodes your encoded data to tree.
        public TreeNode deserialize(String data) {
            String[] strs = data.split(",");
            return dfs(strs);
        }

        int post = -1;
        private TreeNode dfs(String[] strs){
            post++;
            String str = strs[post];
            TreeNode node;
            if(str.equals("&")) return null;
            else{
                node = new TreeNode(Integer.parseInt(str));
                node.left = dfs(strs);
                node.right = dfs(strs);
            }
            return node;
        }
    }
}